<template>
  <div class="dialog-form">
    <el-form ref="driverRef" :model="form" :rules="rules" label-width="110px">
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item label="所属公司" prop="companyId">
            <el-tree-select
              v-model="form.companyId"
              :data="companyList"
              :render-after-expand="true"
              :props="treeProps"
              node-key="id"
              :default-expanded-keys="expandedKeys"
              @change="handleCompanyChange"
              check-strictly
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="司机编号" prop="driverNo">
            <el-input v-model="form.driverNo" placeholder="支持数字、英文" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="司机姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入司机姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="司机性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio
                v-for="dict in bus_driver_sex"
                :key="Number(dict.value)"
                :value="Number(dict.value)"
              >{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责车辆编号" prop="busNo">
            <el-autocomplete
              v-model="form.busNo"
              :fetch-suggestions="querySearch"
              :disabled="!form.companyId"
              placeholder="请选择负责车辆编号"
              @select="handleBusNo"
              @change="form.busLicense = null"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责车牌号" prop="busLicense">
            <el-input v-model="form.busLicense" disabled placeholder="请选择负责车牌号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期" prop="inductionDate">
            <el-date-picker clearable
                            v-model="form.inductionDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择入职日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-switch
              v-model="form.status"
              inline-prompt
              :active-value="1"
              :inactive-value="2"
              inactive-text="禁用"
              active-text="启用"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="居住地址" prop="address">
            <el-input v-model="form.address" type="textarea" :maxlength="100" show-word-limit placeholder="请输入居住地址" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onConfirm">确认</el-button>
    </div>
  </div>
</template>

<script setup>
import { getDriver, addDriver, updateDriver, getSelectData, getBusNo } from "@/api/bus/driver"
import { listVehicle } from "@/api/bus/vehicle"

const { proxy } = getCurrentInstance()
const { bus_driver_sex } = proxy.useDict("bus_driver_sex")

const emits = defineEmits(['cancel', 'confirm'])
const props = defineProps(['companyList'])

const treeProps = {
  label: 'name',
  disabled: (data, node) => {
    return data.state == 2 || data.check == false
  }
}
const expandedKeys = ref([])
const driverRef = ref()
const company = ref([])
const form = ref({
  id: null,
  companyId: null,
  driverNo: null,
  name: null,
  sex: 1,
  busNo: null,
  busLicense: null,
  phone: null,
  inductionDate: null,
  address: null,
  status: 1,
  createTime: null,
  updateTime: null
})
const rules = {
  companyId: [
    { required: true, message: "所属公司不能为空", trigger: "blur" }
  ],
  driverNo: [
    { required: true, message: "司机编号不能为空", trigger: "blur" },
    { pattern: /^[A-Za-z0-9]+$/, message: "司机编号格式不正确", trigger: "blur" }
  ],
  name: [
    { required: true, message: "司机姓名不能为空", trigger: "blur" }
  ],
  sex: [
    { required: false, message: "请选择司机性别", trigger: "change" }
  ],
  busNo: [
    { required: false, message: "负责车辆编号不能为空", trigger: "blur" }
  ],
  busLicense: [
    { required: false, message: "负责车牌号不能为空", trigger: "blur" }
  ],
  phone: [
    { required: false, message: "手机号不能为空", trigger: "blur" },
    { pattern: /^1[3456789]\d{9}$/, message: "手机号格式不正确", trigger: "blur" }

  ],
  status: [
    { required: false, message: "状态不能为空", trigger: "change" }
  ]
}

const pageInit = (id) => {
  getSelectData().then(response => {
    company.value = response.company
  })
  if (id) {
    getDriver(id).then(response => {
      form.value = response.data
      expandedKeys.value = [form.value.companyId]
    })
  }
}

const handleCompanyChange = () => {
  form.value.busNo = null
  form.value.busLicense = null
}

//文本框远程搜索
const querySearch = async (queryString, cb) => {
  let results = []
  try {
    const params = {
      pageNum: 1,
      pageSize: 1000,
      status: 1,
      busNo: queryString,
      companyId: form.value.companyId,
    }
    listVehicle(params).then(res => {
      let result = res.rows
      if (result) {
        //循环放到一个远程搜索需要的数组
        for (let i = 0; i < result.length; i++) {
          const obj = result[i]
          results.push({
            value: obj.busNo,
            id: obj.id,
            status: obj.status,
            busLicense: obj.busLicense
          })
        }
        cb(results)
      } else {
        cb(results)
      }
    })
  } catch (error) {
    console.log(error)
    cb([])
  }
}

const handleBusNo = (obj) => {
  form.value.busLicense = obj.busLicense
}

const onCancel = () => {
  emits('cancel')
}

const onConfirm = () => {
  driverRef.value.validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDriver(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          driverRef.value.resetFields()
          emits('confirm')
        })
      } else {
        addDriver(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          driverRef.value.resetFields()
          emits('confirm')
        })
      }
    }
  })
}

defineExpose({
  pageInit
})

</script>

<style lang="scss" scoped>

</style>